<template>
    <view class="main-box">
        <eui-background type="home" :imageUrl="homeImageUrl">
            <template v-slot:top>
                <view class="home-Head-box">
                    <HomeHead :user="loginInfo.sUserName" :theme="themeStore.theme"/>
                </view>
            </template>
            <template v-slot:bottom>
                <scroll-view 
                    class="home-content" 
                    refresher-enabled='true' 
                    scroll-y="true"
                    refresher-background="white"
					refresher-default-style="white"
                    :refresher-triggered="triggered"
                    :style="{height: scrollHeight + 'px'}"
                    @refresherrefresh="templateUpper"
                >
                    <component
                        v-for="item in sortedComponents"
                        :key="item.sort"
                        :is="item.component"
                    />
                    <view class="no-data" v-if="sortedComponents.length === 0">
                        <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
                        <view class="no-data-text">暂无数据</view>
                        <view  style="margin-top: 40rpx;">
                            <eui-button type="base" title="点击刷新" @click="onRefresh"/>
                        </view>
                    </view>
                </scroll-view>
                <CustomTabBar  current="首页"/>
            </template>
        </eui-background>
    </view>
</template>

<script setup lang="ts">
import service from '../../../common/service';
import { type IRequest } from '../../../types/public'
import { ref, computed, onBeforeMount, watch } from 'vue';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useMainStore } from '@/store/modules/store';
import { useLoginStore } from '@/store/modules/useLoginStore';
import { useThemeStore } from '@/store/themeStore';
import { components } from '@/hooks/useComponents';
import { useModuleDataStore } from '@/store/useModuleDataStore';
import BcmEventType from "@/pages/BcmViews/common/BcmEventType";
import { useRefreshStore } from '@/store/useRefreshStore';
import eventBus from '@/pages/MainViews/eventBus';
import { getDefaultMerchantInfo } from '../../../hooks/bcmInit';
const componentsToLoad = ref<Array<{ name: string; sort: number }>>([]);

const mainStore = useMainStore();
const { loginInfo } = mainStore;
const LoginStore = useLoginStore();
const scrollHeight = ref(0);
const themeStore = useThemeStore();

const moduleDataStore = useModuleDataStore();
const moduleData = moduleDataStore.homePage;

// 获取初始化模块列表
const getLoadModule = async () => {
  componentsToLoad.value = moduleData;
};

const homeImageUrl = computed(() => {
    const baseUrl = `${LoginStore.ImageBaseUrl}/xcxStatic/img`;
    return `${baseUrl}/background-home.png`;
});

const CustomTabBar = components.CustomTabBar
const HomeHead = components.HomeHead;
// 根据name返回对应的组件
const getComponent = (name: string) => components[name] || null;

// 计算属性：排序后的组件
const sortedComponents = computed(() => {
  return componentsToLoad.value
    .map(item => ({ ...item, component: getComponent(item.name) }))
    .filter(item => item.component !== null)
    .sort((a, b) => a.sort - b.sort);
});


onLoad(() => {
    uni.hideTabBar();
})

onShow(async () => {
  initScrollView()
  uni.$emit(BcmEventType.SWITCH_STORE, { msg: '切换门店' })
  if(!!mainStore?.enjoyServiceIp?.EnjoyBCM){
    await getDefaultMerchantInfo()
    uni.$emit(BcmEventType.SWITCH_MERCHANT, { msg: '切换商户' })
  }
});
// 初始化滚动区域高度
const initScrollView =() => {
    setTimeout(() => {
        uni.getSystemInfo({
            success: (res) => {
                const query = uni.createSelectorQuery().in(this);
                query.select('.home-content').boundingClientRect((data:any) => {
                    var screenWidth:number = res.screenWidth;
                    var tabBarHeight:number = (screenWidth * Number.parseInt('118')) / 750;
                    scrollHeight.value = (res.windowHeight - data?.top - tabBarHeight);
                }).exec();
            }
        })
    }, 1000)
}

// 下拉刷新
const refreshStore = useRefreshStore();
const triggered = ref(false);
const templateUpper = (e) => {
    // console.log("108, 下拉刷新触发了!!!!!!!!!!!!!!")
    if (!triggered.value) {
        triggered.value = true;
        let hasTrue = refreshStore.queryRefresh('HomeRefresh')
        if (sortedComponents.value.length > 0 && hasTrue) {
            const moduleName = sortedComponents.value.map(item => item.name)
            for (var i = 0; i < moduleName.length; i++) {
                eventBus.emit('refresh-' + moduleName[i], { keyword: '关键字', page: 1 });
            }
            refreshStore.triggerRefresh('HomeRefresh');
        } else {
            console.log('时间未到, 无需刷新');
            uni.showToast({
                duration: 3500,
                icon: 'none',
                title: `5分钟内不要重复刷新, 请稍后重试`,
            });
        }
        setTimeout(() => {
            triggered.value = false;
        }, 600)
    }
};

// 刷新
const onRefresh = () => {
    refreshStore.refreshTrigger = false;
    refreshStore.triggerRefresh('PortalData');
} 

// 生命周期钩子
onBeforeMount(async () => {
  await getLoadModule();
});

// 监听 模块列表
watch(() => moduleDataStore.homePage,(newVal) => {
    // console.log('首页测试!!!!!!!!!!!', newVal);
    if (newVal.length > 0) {
        refreshStore.triggerRefresh('HomeRefresh');
    }
    componentsToLoad.value = newVal;
  }, { immediate: true }
);

</script>

<style scoped lang="scss">
.main-box {
    height: calc(100vh - 50px);
    ::v-deep .uni-scroll-view-refresh {
        background: #ffffff;
    }
}
.home-Head-box {
    position: relative;
    width: 100%;
    height: 100%;
}
.home-content {
    padding: 10px 10px 0;
    width: 100%;
    box-sizing: border-box;
}

.image-min {
    width: 100%;
    height: 225rpx;
    opacity: 0.6;
    margin-top: -20rpx;
}

.no-data {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 80%;
    background-color: #FFFFFF;
}

.no-data-text {
    text-align: center;
    color: #cccccc;
    font-size: 26rpx;
}
</style>
